//
//  PickerImageView.swift
//  MineModule
//
//  Created by xianquan on 2024/9/9.
//

import TYUIKit
import CommonTools
import TYAlertView
import TZImagePickerController
import MobileCoreServices

class PickerImageView: UIView, TZImagePickerControllerDelegate {
    private let maxCount = 3
    
    private var selectedPhotos: [UIImage] = []
    
    private var selectedAssets: [PHAsset] = []
    
    private var isSelectOriginalPhoto = false
    
    private var imagePickerVc = UIImagePickerController()
    
    var callback: ([UIImage]) -> () = {_ in}
    
    private lazy var collectionView: UICollectionView = {
        let layout = ZLCollectionLeftLayout()
        layout.scrollDirection = .vertical
        layout.minimumInteritemSpacing = adapt(5)
        layout.itemSize = CGSize(width: floor((66)), height: (66))
//        layout.sectionInset = UIEdgeInsets(top: 0, left: adapt(15), bottom: 0, right: adapt(15))
        let collectionView = UICollectionView(frame: bounds, collectionViewLayout: layout)
        addSubview(collectionView)
        collectionView.backgroundColor = .white
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.xw_register(ImageCell.self)
        collectionView.xw_register(AddCell.self)
//        collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: 0)
        
        collectionView.snp.makeConstraints { make in
            make.leading.equalTo(0)
            make.trailing.equalTo(0)
            make.top.equalTo(0)
            make.height.equalTo(74)
        }
        return collectionView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        _ = collectionView
        
        imagePickerVc.delegate = self
        
        adaptScreen()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}

extension PickerImageView {
    func updatePhotos(photo: [UIImage], assets: [PHAsset]) {
        selectedPhotos = photo
        selectedAssets = assets
        collectionView.reloadData()
        callback(selectedPhotos)
    }
    
    func refreshCollectionView(asset: PHAsset?, image: UIImage?){
        if let asset = asset {
            selectedAssets.append(asset)
        }
        if let image = image {
            selectedPhotos.append(image)
        }
        callback(selectedPhotos)
        collectionView.reloadData()
    }
}

extension PickerImageView: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if (selectedPhotos.count < maxCount) {
            return selectedPhotos.count + 1
        }
        return selectedPhotos.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if (indexPath.row < selectedPhotos.count) {
            let cell = collectionView.xw_dequeueReusableCell(withReuseType: ImageCell.self, for: indexPath)
            cell.show(data: selectedPhotos[indexPath.item])
            cell.deleteCallback = {[unowned self] in
                
                if self.collectionView(collectionView, numberOfItemsInSection: 0) <= selectedPhotos.count {
                    selectedPhotos.remove(at: indexPath.item)
                    selectedAssets.remove(at: indexPath.item)
                    collectionView.reloadData()
                    return
                }
                selectedPhotos.remove(at: indexPath.item)
                selectedAssets.remove(at: indexPath.item)
                collectionView.performBatchUpdates {[unowned collectionView] in
                    collectionView.deleteItems(at: [indexPath])
                } completion: {[unowned collectionView] finished in
                    collectionView.reloadData()
                }

            }
            return cell
        }
        else {
            let cell = collectionView.xw_dequeueReusableCell(withReuseType: AddCell.self, for: indexPath)
            
            return cell
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if (indexPath.row < selectedPhotos.count) {
            let assetsArr = NSMutableArray(array: selectedAssets)
            let photoArr = NSMutableArray(array: selectedPhotos)
            guard let imagePickerVc = TZImagePickerController(selectedAssets: assetsArr , selectedPhotos: photoArr , index: indexPath.item) else {return}
            imagePickerVc.maxImagesCount = maxCount
            imagePickerVc.allowPickingOriginalPhoto = true
            imagePickerVc.showSelectedIndex = true
            imagePickerVc.didFinishPickingPhotosHandle = {[self] photos, assets, isSelectOriginalPhoto in
                guard let photo = photos, let assets = assets as? [PHAsset] else {return}
                updatePhotos(photo: photo, assets: assets)
            }
            imagePickerVc.modalPresentationStyle = .fullScreen
            TY_TopViewController().present(imagePickerVc, animated: true)
        }
        else {
            TYAlertView.showCommonAlert(message: nil, style: .actionSheet, buttonTitles: ["相机", "相册"], cancelButtonTitle: "取消") {[self] alert, index in
                if (index == 1) {
                    imagePickerVc.sourceType = .camera
                    imagePickerVc.mediaTypes = [kUTTypeImage as String] //["public.image"]
                    TY_TopViewController().present(imagePickerVc, animated: true)
                }
                else if (index == 2) {
                    if let imagePickerVc = TZImagePickerController(maxImagesCount: maxCount, columnNumber: 4, delegate: self, pushPhotoPickerVc: true) {
                        if !selectedAssets.isEmpty {
                            imagePickerVc.selectedAssets = NSMutableArray(array: selectedAssets)
                        }
                        imagePickerVc.allowTakeVideo = true
                        imagePickerVc.allowTakeVideo = false
                        imagePickerVc.iconThemeColor = .selectedColor
                        imagePickerVc.showPhotoCannotSelectLayer = true
                        imagePickerVc.cannotSelectLayerColor = UIColor(white: 1, alpha: 0.8)
                        imagePickerVc.allowPickingImage = true
                        imagePickerVc.allowPickingOriginalPhoto = true
                        imagePickerVc.sortAscendingByModificationDate = true
                        imagePickerVc.showSelectedIndex = true
                        imagePickerVc.didFinishPickingPhotosHandle = {[self] photos, assets, isSelectOriginalPhoto in
                            guard let photo = photos, let assets = assets as? [PHAsset] else {return}
                            updatePhotos(photo: photo, assets: assets)
                        }
                        imagePickerVc.modalPresentationStyle = .fullScreen
                        TY_TopViewController().present(imagePickerVc, animated: true)
                    }
                    
                    
                }
            }
        }
    }
    
}

extension PickerImageView: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true)
        let image = info[.originalImage] as? UIImage
        TZImageManager.default().savePhoto(with: image) {[self] asset, error in
            if let error = error {
                XWLog(value: "图片保存失败\(error)")
            }
            else {
                refreshCollectionView(asset: asset, image: image )
            }
        }
    }
    
    
}



extension PickerImageView {
    class ImageCell: UICollectionViewCell {
        
        var deleteCallback = {}
        
        private lazy var iv: UIImageView = {
            let iv = UIImageView(image: nil, in: contentView) { make in
                make.edges.equalTo(UIEdgeInsets(top: 6, left: 0, bottom: 0, right: 6))
            }
            iv.contentMode = .scaleAspectFill
            iv.cut(withRadius: 8)
            return iv
        }()
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            _ = iv
            let deleteBtn = UIButton(title: nil, titleColor: nil, imageInBundle: .mineModule("icon_delete"), font: nil, in: contentView) { make in
                make.top.equalTo(-2)
                make.trailing.equalTo(2)
                make.width.height.equalTo(20)
            }
            deleteBtn.addBlock(for: .touchUpInside) {[unowned self] _ in
                deleteCallback()
            }
            adaptScreen()
        }
        
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        func show(data: UIImage) {
            iv.image = data
        }
    }
}

extension PickerImageView {
    class AddCell: UICollectionViewCell {
        override init(frame: CGRect) {
            super.init(frame: frame)
            let bg = UIView(backgroundColor: .blackf6, in: contentView) { make in
                make.edges.equalTo(UIEdgeInsets(top: 6, left: 0, bottom: 0, right: 6))
            }
            bg.cut(withRadius: 8)
            let hView = UIView(backgroundColor: UIColor(hexString: "#bebebe"), in: bg) { make in
                make.leading.equalTo(15)
                make.trailing.equalTo(-15)
                make.height.equalTo(4)
                make.centerY.equalToSuperview()
            }
            hView.cut(withRadius: 2)
            let vView = UIView(backgroundColor: UIColor(hexString: "#bebebe"), in: bg) { make in
                make.top.equalTo(15)
                make.bottom.equalTo(-15)
                make.width.equalTo(4)
                make.centerX.equalToSuperview()
            }
            vView.cut(withRadius: 2)
            
            adaptScreen()
        }
        
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
}
